﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AgencyEntityLib.BaseEntity;

using FormControllers;
using Ecopsy.DataTier;
using Ecopsy.Tools;

public partial class Ctl_ctlClientEditorNew : System.Web.UI.UserControl
{
    public const string qClientID = "ClientID";
    wsFace ws = (wsFace)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Face];

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
         //   MyDataBind();

        }
        Init();

    }

    protected override void OnDataBinding(EventArgs e)
    {
        //base.OnDataBinding(e);
    }

    private void Init()
    {
        //привязать событие открыть закрыть lvContactFace
        if (lvContactFaces.EditItem != null)
        {

            Ctl_ctlContactFace r1 = (Ctl_ctlContactFace)lvContactFaces.EditItem.FindControl("ctlContactFace1");
            r1.OnButtonClick = OnContactFaceClick;
            r1.OnMyDataChanged = OnContactFaceClick;
        }

        // проставить статус редактирования
        iAdmin_Page.SetAlertForTextBox_Static (this.Controls, "TextBox", "onChange", "ShowAlert()");
        // привязать editbox  к статусу редактирования
        //SetMsg_EditStatus();

        //ctlCalendar1.OnPeriodChange = CalendarReBind; 
    }

    private void MyDataBind()
    {
        lvCurator.DataSource = ClientAsList;
        lvStatus.DataSource = ClientAsList;
        lvCategoria.DataSource = ClientAsList;
        lvContactFaces.DataSource = GetContactFaces(null);
        //lvTask.DataSource = GetClientTasks(null);
        DataBind();
    }

    protected List<grdClient> ClientAsList
    {
        get
        {
            List<grdClient> r = new List<grdClient>();
            r.Add(grdClient);
            return r;
        }

    }

    protected grdClient grdClient
    {
        get { return new grdClient(Client); }
    }

    protected Client Client
    {
        get 
        {
            if (string.IsNullOrEmpty (ClientID))
                    return new Client ();
            else 
                    return ws.GetClient(ClientID); 
        }
    }

    protected string ClientID
    {
        get { return Request.QueryString[qClientID]; }
    }

    protected bool IsNewRecord
    {
        get 
        {
            if (string.IsNullOrEmpty(ClientID))
                return true;

            return (ClientID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1); 
        }
    }

    private void ReadForm()
    {

        Client.Name = txtClientName.Text;
        // Client.Describe = txtDescribe.Text;

        Client.Phones = txtTelefon.Text;
        Client.Email = txtMail.Text;
        Client.URL = txtUrl.Text;
        Client.Adress = txtAdress.Text;

        Client.INN = txtInn.Text;
        Client.KPP = txtKPP.Text;
        Client.Account = txtAccount.Text;

    }


    #region Клиент

    #region Обновление
    Func<ListViewDataItem, bool> LvUpdCmd;

    private bool UpdateCurator(ListViewDataItem item)
    {
        DropDownList lb = (DropDownList)item.FindControl("cmbEmpl");
        if (null == lb.SelectedItem) return true;
        Client.CuratorID = lb.SelectedItem.Value;
        return true;
    }

    private bool UpdateStatus(ListViewDataItem item)
    {
        
        if (string.Empty == hf_tvStatus.Value) return true;
        TreeDictionaryItem r1 = iPageController.TreeDictionaryContext.GetClientStatus();
        TreeDictionaryItemValue f = r1.BuildValue(hf_tvStatus.Value);
        Client.StatusValue = f;
        return true;
    }

    private bool UpdateCategoria(ListViewDataItem item)
    {
        if (string.Empty == hf_tvCategoria.Value) return true;
        TreeDictionaryItem r1 = iPageController.TreeDictionaryContext.GetClientsCategory();
        TreeDictionaryItemValue f = r1.BuildValue(hf_tvCategoria.Value);
        Client.Ctegoria = f;
        return true;
    }

    private bool UpdateTask(ListViewDataItem item)
    {
        return true;
    }

    private bool UpdateContactFaces(ListViewDataItem item)
    {
        return true;
    }

    #endregion

    protected string GetCuratorAsText()
    {
        Employeer r = Client.GetCurator();
        if (null == r) return string.Empty;
        return r.ShortName;
    }

    protected string GetStatusAsText()
    {
        return Client.GetTxtClientStatus();
    }

    protected string GetCategoriaAsText()
    {
        return Client.GetTxtClientCategoria();
    }

    protected void ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        //Client.ContactFaces.Reset();
        //List<string> l = new List<string>();
        //foreach (ContactFace item in Client.ContactFaces)
        //    if (item.ID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1) l.Add(item.ID);
        //foreach (string s in l)
        //    Client.ContactFaces.Remove(s);

    }
    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;

        ListView lv = (ListView)sender;

        switch (lv.ID)
        {
            case "lvCurator":
                LvUpdCmd = UpdateCurator;
                break;
            case "lvStatus":
                LvUpdCmd = UpdateStatus;
                break;
            case "lvCategoria":
                LvUpdCmd = UpdateCategoria;
                break;
            case "lvContactFaces":
                LvUpdCmd = UpdateContactFaces;
                break;
            case "lvTask":
                LvUpdCmd = UpdateContactFaces;
                break;

        }

        switch (e.CommandName)
        {
            case "Edit":
                {

                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;

                    break;
                }
            case "Insert":
                {

                    break;
                }
            case "Update":
                {
                    if (LvUpdCmd((ListViewDataItem)e.Item)) lv.EditIndex = -1;
                    SetMsg_EditStatus();
                    break;
                }
            case "Delete":
                {
                    //DeleteCustomer(e.CommandArgument as string);
                    break;
                }
        }

        switch (lv.ID)
        {
            case "lvContactFaces":
                lv.DataSource = GetContactFaces(null);
                break;
            case "lvTask":
                lv.DataSource = GetClientTasks(null);
                break;
            default:
                lv.DataSource = ClientAsList;
                break;
        }
        lv.DataBind();
        iAdmin_Page.SetAlertForTextBox_Static (this.Controls, "TextBox", "onChange", "ShowAlert()");



    }
    protected void ItemEditing(object sender, ListViewEditEventArgs e)
    {
        ListView lv = (ListView)sender;
        switch (lv.ID)
        {
            case "lvCurator":
                {

                    /// lvCurator
                    DropDownList d1 = (DropDownList)lvCurator.EditItem.FindControl("cmbEmpl");
                    EmployeeList.sqlLoadStatment st = new EmployeeList.sqlLoadStatment();
                    st.Lexeme = string.Empty;
                    EmployeeList l = GetEmplList(st);

                    Employeer[] SortResult = l.ToArray<Employeer>();
                    //заряжаем comparer функцией сортировки 
                    Ecopsy.Tools.WhereCondition.TSortCondition s = new WhereCondition.TSortCondition() { SortField = "FulName" };
                    s.fnOrderBy = WhereCondition.SortFunctions.fOrderBy;
                    // Сортируем
                    Array.Sort(SortResult, s);
                    //Заполняем cmb
                    foreach (Employeer item in SortResult)
                    {
                        ListItem nl = new ListItem(item.FullName, item.ID);
                        d1.Items.Add(nl);
                    }
                    break;
                }
            case "lvTask":
                {

                    break;
                }
        }


    }
    protected void ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        // Проверить тип строчки - если это строчка редактирования - зацепить требуемый DS

        ListView lv = (ListView)sender;
        switch (lv.ID)
        {
            case "lvStatus":
                {
                    object tv = e.Item.FindControl("tvStatus");
                    if (null != tv)
                    {
                        ((TreeView)tv).DataSource = GetEmployeeSource("chTree_Status", "ctl00_cphHead_hf_tvStatus");
                        ((TreeView)tv).DataBind();

                    }
                    break;
                }

            case "lvCategoria":
                {
                    object tv = e.Item.FindControl("tvCategoria");
                    if (null != tv)
                    {
                        ((TreeView)tv).DataSource = GetCategoriaSource("chTree_Categoria", "ctl00_cphHead_hf_tvCategoria");
                        ((TreeView)tv).DataBind();

                    }
                    break;
                }

        }

    }

    ////поиск в списке сотрудников
    //protected void OnClick_btnFindEmpl(object sender, EventArgs e)
    //{
    //    TextBox txt=(TextBox) lvCurator.EditItem .FindControl ("txtFindEmpl");
    //    iEmplListWhere Filtr = new iEmplListWhere();
    //    Filtr.SetPropertyList(txt.Text);        
    //    updCurator.Update();
    //}

    private EmployeeList GetEmplList(EmployeeList.sqlLoadStatment Filtr)
    {
        return ws.GetEmplList(Filtr);
    }

    //Сохранение
    protected void btnSave_Click(object sender, EventArgs e)
    {
        ReadForm();
        Client fc = (Client)ws.SaveFace(Client);
        if (Client.ID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1)//режим вставки?
        {

            Response.Redirect("~\\iCRM_ClientEditor.aspx?" + qClientID + "=" + fc.ID);

        }
        lblClientStatus.CssClass = GlobalConstants.cssHidden;
    }
    /// <summary>
    /// соббщение о состоянии записи
    /// </summary>
    protected void SetMsg_EditStatus()
    {
        lblClientStatus.DataBind();
        updStatus.Update();
    }
    bool IsTaskEditorchanged = false;
    // Пказать скрыть предупрежденеие о несохраненных данных    
    protected string GetStateVisible()
    {
        if (IsTaskEditorchanged) return string.Empty;
        if (string.IsNullOrEmpty(ClientID)) return string.Empty;

        if (ClientID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1) return string.Empty;
        if (Client.State != EntityState.Loaded) return string.Empty;
        //Client.ContactFaces().Reset ();
        foreach (Entity item in Client.GetContactFaces())
        {
            if (item.State != EntityState.Loaded) return string.Empty;
        }



        return "hidden";

    }

    #region Визуальные источники
    protected virtual F_TreeDataSource GetEmployeeSource(string _NodeClass, string _HfId)
    {
        // Инициализировать RbCheckBox 
        TreeNodeFormatter_Rb.TreeRbContext f = new TreeNodeFormatter_Rb.TreeRbContext()
        {
            DivClass = "",
            NodeClass = _NodeClass,
            HfId = _HfId,

            // опредеить функцию решающую нажат чек бокс или нет 
            OnChBind = delegate(TreeEntitySingle _tr)
            {
                return false;
            }
        };


        // определить делегат поставляющий класс определяющий формат ноды в дереве
        Func<TreeEntitySingle, F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData> formatter = delegate(TreeEntitySingle _tr)
        {

            return (F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData)new TreeNodeFormatter_Rb(_tr, f);
        };

        // сформировать источник данных виз. элемента
        return new F_TreeDataSource(iPageController.TreeDictionaryContext.GetClientStatus(), formatter);

    }
    protected virtual F_TreeDataSource GetCategoriaSource(string _NodeClass, string _HfId)
    {
        // Инициализировать RbCheckBox 
        TreeNodeFormatter_Rb.TreeRbContext f = new TreeNodeFormatter_Rb.TreeRbContext()
        {
            DivClass = "",
            NodeClass = _NodeClass,
            HfId = _HfId,

            // опредеить функцию решающую нажат чек бокс или нет 
            OnChBind = delegate(TreeEntitySingle _tr)
            {
                return false;
            }
        };


        // определить делегат поставляющий класс определяющий формат ноды в дереве
        Func<TreeEntitySingle, F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData> formatter = delegate(TreeEntitySingle _tr)
        {
            return (F_TreeDataSource.F_TreeDataSourceView.F_TreeHierarchyData)new TreeNodeFormatter_Rb(_tr, f);
        };

        // сформировать источник данных виз. элемента
        return new F_TreeDataSource(iPageController.TreeDictionaryContext.GetClientsCategory(), formatter);

    }
    #endregion

    #endregion

    #region Контактные лица
    protected void btnAddContactFace_Click(object sender, EventArgs e)
    {
        
        ContactFace NewFace = new ContactFace() { ID = GlobalConstants.qPrefNEW_RECORD + Guid.NewGuid().ToString(), FirstName = " Новая запись", ClientID = ClientID };
        ws.SaveFace(NewFace);
        lvContactFaces.EditIndex = 0;
        lvContactFaces.DataSource = GetContactFaces(null);
        lvContactFaces.DataBind();

    }
    /// <summary>
    /// Вернуть упорядоченный список контактеров с условием - сортировка по фамилии ,  несохраненная в БД запись - первая в списке
    /// </summary>
    /// <returns></returns>
    //protected ContactFace[] ContactWorkers
    //{
    //    get 
    //    {
    //        ContactFace [] w= Client.GetContactFaces().ToArray<ContactFace>();
    //        Array.Sort(w, new WorkerSorter ());
    //        return w;
    //    }
    //}

    protected ContactFace[] GetContactFaces(ContactFace AddFace)
    {

        ContactFaceList l = Client.GetContactFaces();
        List<ContactFace> lst = l.ToList<ContactFace>();
        if (null != AddFace) lst.Add(AddFace);
        ContactFace[] res = lst.ToArray<ContactFace>();
        Array.Sort(res, new WorkerSorter());
        return res;
    }

    protected grdTask[] GetClientTasks(Task AddTask)
    {

        TaskList l = Client.GetTasks();
        List<grdTask> lst = new List<grdTask>();
        foreach (Task item in l)
        {
            grdTask t = new grdTask(item);
            lst.Add(new grdTask(item));
        }
        if (null != AddTask) lst.Add(new grdTask(AddTask));
        grdTask[] res = lst.ToArray<grdTask>();
        Array.Sort(res, new grdTaskSorter());
        return res;
    }

    protected Contact[] ContactItems(ContactFace Worker)
    {
        Contact[] c = Worker.ContactList.GetSortedList();
        return c;
    }

    private string GetTxt(Control item, string name)
    {
        TextBox hf = (TextBox)item.FindControl(name);
        return hf.Text;
    }

    protected void BntRemoveWorker_Click(object sender, EventArgs e)
    {
        //ImageButton btn =(ImageButton) sender ;
        //Client.ContactFaces.Remove(btn.CommandArgument);
        //lvContactFaces.DataSource = ContactWorkers;
        //lvContactFaces.DataBind();
        //btnSave_Click(null, null); 

    }

    protected void btnSaveWorker_Click(object sender, EventArgs e)
    {

    }

    protected void lvContactFaces_ItemInserting(object sender, ListViewInsertEventArgs e)
    {

    }
    #endregion



    protected void lvContactFaces_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        object r = e.Item.FindControl("hfContactFaceId");
        if (null != r)
        {
            ListView lv = (ListView)e.Item.FindControl("lvContactItems");

            ContactFace w = (ContactFace)Client.GetContactFaces()[((HiddenField)r).Value];
            lv.DataSource = ContactItems(w);
            lv.DataBind();

        }
    }

    protected void BntRemoveTask_Click(object sender, ImageClickEventArgs e)
    {
        wsTask ws = (wsTask)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Task];        
        ImageButton btn = (ImageButton)sender;
        Task t = ws.GetTask(btn.CommandArgument);
        t.DestroyMySelf();
        ws.SaveTask(t);
        OnTaskEditorClick();
    }



    private class WorkerSorter : IComparer<ContactFace>
    {

        #region IComparer<Entity> Members

        public int Compare(ContactFace x, ContactFace y)
        {
            if (y.ID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1) return 1;
            return x.FullName.CompareTo(y.FullName);
        }

        #endregion
    }

    /// <summary>
    /// сортировать по дате дедлайна - запись с первиксонм - новая - первая
    /// </summary>
    private class grdTaskSorter : IComparer<grdTask>
    {

        #region IComparer<Entity> Members

        public int Compare(grdTask x, grdTask y)
        {
            if (x.Task.ID.IndexOf(GlobalConstants.qPrefNEW_RECORD) > -1) return 1;
            return 0;
            //return x.Task.dtFinish.CompareTo(y.Task.dtFinish);
        }

        #endregion
    }


    protected void btnAddTask_Click(object sender, EventArgs e)
    {
        //ws_Task ws = new ws_Task();        
        //Task NewTask = ws.GetNewTask(GlobalConstants.qPrefNEW_RECORD + Guid.NewGuid().ToString());
        //NewTask.ClientID = ClientID;
        //NewTask.EmplID =Client.CuratorID ;                 
        //lvTask.EditIndex = 0;
        //lvTask.DataSource = GetClientTasks(NewTask);
        //lvTask.DataBind();
        //ItemEditing(lvTask, null);
    }

    protected void ReverceTaskState(object sender, EventArgs e)
    {
        string s = ((Button)sender).CommandArgument;
        wsTask ws = (wsTask)GlobalConstants.CurrentAgency.WS_FactoryList[WS_FactoryList.wsKey_Task];        
        Task t = ws.GetTask(s);
        t.IsClosed = !t.IsClosed;
        ws.SaveTask(t);
        OnTaskEditorClick();

    }

    protected Func<bool> GetLvTask_OnButtonClick()
    {
        return OnTaskEditorClick;
    }
    protected bool OnTaskEditorClick()
    {
        //    lvTask.EditIndex = -1;
        //    lvTask.DataSource = GetClientTasks(null);
        //    lvTask.DataBind();
        return true;
    }
    protected bool OnTaskEditorDataChanged()
    {
        IsTaskEditorchanged = true;
        SetMsg_EditStatus();
        return true;
    }

    protected bool OnContactFaceClick()
    {
        lvContactFaces.EditIndex = -1;
        lvContactFaces.DataSource = GetContactFaces(null);
        lvContactFaces.DataBind();
        return true;
    }    

}
